#include <odbc++/drivermanager.h>
#include <odbc++/connection.h>
#include <odbc++/resultset.h>
#include <odbc++/resultsetmetadata.h>
#include <odbc++/preparedstatement.h>

//#include <cstdio>
#include <iostream>

using namespace odbc;
using namespace std;


auto_ptr<Connection> con;

void	SQLConnect(const char *connectionInfo)
{
	cout << "Connecting to " << connectionInfo
					<< "..." << flush;
	con = auto_ptr<Connection>(DriverManager::getConnection(connectionInfo));
	cout << " done." << endl;
}


// odbc ISO YYYY-MM-DD HH24:MI:SS.FFF
//
static void timevalToDate(const struct timeval *in, char *out)
{
   struct tm *ti = localtime(&in->tv_sec);
	sprintf(out, "%04d-%02d-%02d %02d:%02d:%02d.%d", 
			ti->tm_year + 1900, ti->tm_mon + 1, ti->tm_mday,
			ti->tm_hour, ti->tm_min, ti->tm_sec,
			in->tv_usec);
}

void	SQLRead()
{
	std::auto_ptr<PreparedStatement> pstmt = std::auto_ptr<PreparedStatement>(con->prepareStatement
		(
			"SELECT  "
			"  src_dns.hostname AS src_host, "
			"  src_dns.ip AS src_ip, "
			"  dst_dns.hostname AS dst_host, "
			"  dst_dns.ip as dst_ip, "
			"  connections.port_src as src_port, "
			"  connections.port_dst as dst_port, "
			"  connections.first_seen as first_seen, "
			"  connections.last_seen as last_seen, "
			"  connections.volume as volume "
			"FROM "
			" connections "
			" INNER JOIN dnsentry src_dns ON (connections.src_ip_serial=src_dns.serial) "
			" INNER JOIN dnsentry dst_dns ON (connections.dst_ip_serial=dst_dns.serial) "
		));
		
//		("SELECT * FROM connections")); // WHERE last_seen > ?"
//	pstmt->setString(1, resolvedName);
	auto_ptr<ResultSet> rs = auto_ptr<ResultSet>(pstmt->executeQuery());
	while(rs->next()) {
    rs->getRow();

	 cout << rs->getString("src_host") << " "
		  << rs->getString(2) << " " << endl;
	}
}

